<?php
//error_reporting(1);

set_time_limit(0);
global $wpdb;


function save_image($img, $id){
	global $wpdb;
    $fullname = $id."-".basename($img);
	$pInf=wp_upload_dir();
	$basePath=$pInf['basedir'];

    if(file_exists($basePath."/companiesLogo/".$fullname)){
       unlink($basePath."/companiesLogo/".$fullname);
    }
	
    $ch = curl_init ($img);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $rawdata=curl_exec($ch);
    curl_close ($ch);
    $fp = fopen($basePath."/companiesLogo/".$fullname,'x');
    fwrite($fp, $rawdata);
    fclose($fp);
	$wpdb->query("update companies set logoFile='".$fullname."', importDone=1 Where companyID=".$id);
}

$myrows = $wpdb->get_results( "SELECT * FROM companies Where importDone=0 AND TRIM(logoURL)!='' Limit 50");

//print_r($myrows);
//exit;


foreach($myrows as $row){
	save_image($row->logoURL,$row->companyID);
}

$myrows =(array) $wpdb->get_results( "SELECT * FROM companies Where importDone=0");
if(count($myrows)==0) echo "All Done"; else echo "There Are ".count($myrows)." Records Waiting for Processing. Please Refresh It Again";



